package com.lcq.springbootcreate.project.fliter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class WebLogAspect {
    @Pointcut("execution(public * com.lcq.springbootcreate.project.controller.*.*(..))")
    public void webLog() {

    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 利用分发机器，获取到分发到内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 利用分发的内容，获取到请求
        HttpServletRequest request = attributes.getRequest();
        String URL = request.getRequestURL().toString();
        String AGRS = Arrays.toString(joinPoint.getArgs());
        System.out.println("AOP拦截到的参数:"+"URL:"+URL+"  ------  "+"AGRS:"+AGRS);
    }

    @AfterReturning(returning = "res", pointcut = "webLog()")
    public void doAfterReturning(Object res) throws JsonProcessingException {
        System.out.println("返回结果:"+new ObjectMapper().writeValueAsString(res).toString());
    }
}
